package com.silverbox.shopper.service.info.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.silverbox.core.util.DateUtils;
import com.silverbox.shopper.entity.extend.*;
import com.silverbox.sweeporder.common.util.DistanceUtil;
import com.silverbox.sweeporder.controller.index.vo.PromotionInfoVO;
import com.silverbox.sweeporder.controller.index.vo.ShopAddressInfoVO;
import com.silverbox.sweeporder.controller.waimai.outvo.ShopBusinessInfoVo;
import com.silverbox.waimai.mapper.MsgRecordMapper;

import com.silverbox.core.util.CalendarUtil;
import com.silverbox.shopper.mapper.*;
import com.silverbox.waimai.entity.TakeOutBilling;
import com.silverbox.waimai.entity.TakeOutConfig;
import com.silverbox.waimai.mapper.TakeOutBillingMapper;
import com.silverbox.waimai.mapper.TakeOutConfigMapper;
import com.silverbox.waimai.mapper.TakeOutPeriodMapper;
import com.silverbox.waimai.mapper.TakeOutThirdShopInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.entity.BusinessEncoding;
import com.silverbox.shopper.entity.BusinessWhiteList;
import com.silverbox.shopper.entity.DiningArea;
import com.silverbox.shopper.entity.EpayShopConfig;
import com.silverbox.shopper.entity.Machine;
import com.silverbox.shopper.entity.OuterSupport;
import com.silverbox.shopper.entity.PayChannel;
import com.silverbox.shopper.entity.Qrcode;
import com.silverbox.shopper.entity.ReserveBasicInfo;
import com.silverbox.shopper.entity.Shopper;
import com.silverbox.shopper.entity.ShopperConfig;
import com.silverbox.shopper.entity.ShopperExtend;
import com.silverbox.shopper.entity.ShopperNotice;
import com.silverbox.shopper.entity.ShopperService;
import com.silverbox.shopper.entity.ThirdPartyAuthorization;
import com.silverbox.shopper.entity.ThirdUserInfo;
import com.silverbox.shopper.mapper.BusinessEncodingMapper;
import com.silverbox.shopper.mapper.BusinessWhiteListMapper;
import com.silverbox.shopper.mapper.DecorationShopConfigDetailMapper;
import com.silverbox.shopper.mapper.DecorationShopConfigMapper;
import com.silverbox.shopper.mapper.DecorationSuitShopMapper;
import com.silverbox.shopper.mapper.DiningAreaMapper;
import com.silverbox.shopper.mapper.EmployeeMapper;
import com.silverbox.shopper.mapper.EpayShopConfigMapper;
import com.silverbox.shopper.mapper.InvoiceMapper;
import com.silverbox.shopper.mapper.MachineConfigMapper;
import com.silverbox.shopper.mapper.MachineMapper;
import com.silverbox.shopper.mapper.OuterSupportMapper;
import com.silverbox.shopper.mapper.PayChannelMapper;
import com.silverbox.shopper.mapper.QrcodeMapper;
import com.silverbox.shopper.mapper.ReserveBasicInfoMapper;
import com.silverbox.shopper.mapper.ShopperConfigMapper;
import com.silverbox.shopper.mapper.ShopperExtendMapper;
import com.silverbox.shopper.mapper.ShopperMapper;
import com.silverbox.shopper.mapper.ShopperNoticeMapper;
import com.silverbox.shopper.mapper.ShopperServiceMapper;
import com.silverbox.shopper.mapper.ThirdPartyAuthorizationMapper;
import com.silverbox.shopper.mapper.ThirdUserInfoMapper;
import com.silverbox.shopper.entity.extend.DecorationShopConfigDetailExtend;
import com.silverbox.shopper.entity.extend.EmployeeExtend;
import com.silverbox.shopper.entity.extend.InvoiceServiceInfo;
import com.silverbox.shopper.entity.extend.ShopperActivities;
import com.silverbox.shopper.entity.extend.ShopperAndParent;
import com.silverbox.shopper.entity.extend.ShopperInfo;
import com.silverbox.shopper.service.info.ShopperInfoService;
import org.springframework.util.CollectionUtils;

@Service
public class ShopperInfoServiceImpl implements ShopperInfoService {

	@Autowired
	private ShopperMapper shopperMapper;

	@Autowired
	private DiningAreaMapper diningAreaMapper;

	@Autowired
	private ShopperConfigMapper shopperConfigMapper;

	@Autowired
	private ShopperNoticeMapper shopperNoticeMapper;

	@Autowired
	private ThirdPartyAuthorizationMapper tpaMapper;

	@Autowired
	private ThirdUserInfoMapper thirdUserInfoMapper;

	@Autowired
	private ShopperExtendMapper shopperExtendMapper;

	@Autowired
	private ShopperServiceMapper shopperServiceMapper;

	@Autowired
	private EpayShopConfigMapper epayShopConfigMapper;

	@Autowired
	private EmployeeMapper employeeMapper;

	@Autowired
	private MachineMapper machineMapper;

	@Autowired
	private BusinessEncodingMapper businessEncodingMapper;
	
	@Autowired
	private BusinessWhiteListMapper businessWhiteListMapper;
	
	@Autowired
	private DecorationShopConfigMapper decorationShopConfigMapper;
	
	@Autowired
	private DecorationSuitShopMapper decorationSuitShopMapper;
	
	@Autowired
	private DecorationShopConfigDetailMapper decorationShopConfigDetailMapper;
	
	@Autowired
	private MachineConfigMapper machineConfigMapper;

	@Autowired
	private OuterSupportMapper outerSupportMapper;
	
	@Autowired
	private PayChannelMapper payChannelMapper;
	
	@Autowired
	private QrcodeMapper qrcodeMapper;
	
	@Autowired
	private InvoiceMapper invoiceMapper;

	@Autowired
    private TakeOutThirdShopInfoMapper takeOutThirdShopInfoMapper;
	@Autowired
    private TakeOutBillingMapper takeOutBillingMapper;
	@Autowired
    private TakeOutPeriodMapper takeOutPeriodMapper;
    @Autowired
    private HotGoodsWeekMapper hotGoodsWeekMapper;
    @Autowired
    private TakeOutConfigMapper takeOutConfigMapper;
    @Autowired
    private ThirdPartyAuthorizationMapper thirdPartyAuthorizationMapper;

	@Autowired
	private ReserveBasicInfoMapper reserveBasicInfoMapper;

	@Autowired
    private RuleMapper ruleMapper;

	@Autowired
	private MsgRecordMapper msgRecordMapper;

	@Override
	public DiningArea getDiningAreaById(Integer Id) {
		return diningAreaMapper.getDiningAreaById(Id);
	}

	@Override
	public DiningArea getDiningAreaByUid(String uid) {
		return diningAreaMapper.getDiningAreaByUid(uid);
	}

	@Override
	public ShopperAndParent getShopperAndParent(Integer storeId) {
		return shopperMapper.getShopperAndParent(storeId);
	}

	@Override
	public Shopper getShopper(Integer storeId) {
		return shopperMapper.selectByPrimaryKey(storeId);
	}
	
	@Override
	public List<ShopperConfig> getShopperConfig(ShopperConfig shopperConfig) {
		return shopperConfigMapper.getShopperConfig(shopperConfig);
	}

	@Override
	public ShopperNotice getShopperNotice(Integer storeId, String nowDate) {
		return shopperNoticeMapper.getShopperNewestNotice(storeId, nowDate);
	}

	@Override
	public ThirdUserInfo getThirdUserInfo(String buyerId, Integer source) {
		ThirdUserInfo thirdUserInfo = thirdUserInfoMapper.selectByBuyerId(buyerId, source);
		//解决用户信息存储时user_id和thirdUserId存反了问题
		if (thirdUserInfo != null && thirdUserInfo.getUserId() != null && thirdUserInfo.getThirdUserId() != null) {
			if (thirdUserInfo.getThirdUserId().length() > thirdUserInfo.getUserId().length()) {
				String userId = thirdUserInfo.getThirdUserId();
				thirdUserInfo.setThirdUserId(thirdUserInfo.getUserId());
				thirdUserInfo.setUserId(userId);
			}
		}
		if (thirdUserInfo != null && thirdUserInfo.getUserId() != null && Utils.isEmpty(thirdUserInfo.getThirdUserId())) {
			thirdUserInfo.setThirdUserId(thirdUserInfo.getUserId());
			thirdUserInfo.setUserId(thirdUserInfo.getThirdUserId());
		}
		return thirdUserInfo;
	}

	@Override
	public ThirdPartyAuthorization getThirdPartyAuthorization(Integer storeId) {
		return tpaMapper.selectByStoreId(storeId);
	}

	@Override
	public ShopperExtend getShopperExtend(Integer storeId) {
		return shopperExtendMapper.selectByStoreId(storeId);
	}

	@Override
	public List<ShopperActivities> getShopperActivities(String shopId, String nowDate) {
		return shopperMapper.getShopperActivities(shopId, nowDate);
	}

	@Override
	public List<ShopperService> getShopperService(Integer storeId) {
		return shopperServiceMapper.getShopperService(storeId);
	}

	@Override
	public EpayShopConfig getEpayShopConfig(Integer storeId) {
		return epayShopConfigMapper.getEpayShopConfig(storeId);
	}

	@Override
	public EmployeeExtend getRelTableEmployee(Integer tableNo) {
		return employeeMapper.getRelTableEmployee(tableNo);
	}

	@Override
	public List<Machine> getMachineByStoreId(Integer storeId) {
		return machineMapper.getMachineByStoreId(storeId);
	}

	@Override
	public Map<String, Object> getShopperRenovationDefaultConfig(int decorationType) {
		return decorationShopConfigMapper.getShopperRenovationDefaultConfig(decorationType);
	}

	@Override
	public List<Long> getShopperRenovationByStoreId(Integer storeId,int decorationType) {
		return decorationSuitShopMapper.getShopperRenovationByStoreId(storeId,decorationType);
	}

	public String getShopperRenovationByShopperId(Long configId,int decorationType) {
		return decorationShopConfigMapper.getShopperRenovationByShopperId(configId,decorationType);
	}
	@Override
	public Integer getWhiteBusinessStatus(String code) {
		return businessEncodingMapper.getWhiteBusinessStatus(code);
	}

	@Override
	public boolean getIsOpenWhiteBusiness(Integer storeId, String code) {
		Integer businessStatus = businessEncodingMapper.getWhiteBusinessStatus(code);
		if(new Integer(0).equals(businessStatus)){
			return false;
		} else if (new Integer(2).equals(businessStatus)) {
			return true;
		} else {
			Integer isOpenWhiteBusiness = businessWhiteListMapper.getIsOpenWhiteBusiness(storeId,"sweep_alipay_cancel");
			if (null!=isOpenWhiteBusiness && new Integer(1).equals(isOpenWhiteBusiness)) {
				return false;
			}else{
				return true;
			}
		}
	}

	@Override
	public ShopperInfo getShopperInfo(Integer storeId, String nowDate) {
		return shopperMapper.getShopperInfo(storeId,nowDate);
	}

	@Override
	public int saveOrUpdateThirdUserInfo(ThirdUserInfo thirdUserInfo) {
		ThirdUserInfo userInfo = thirdUserInfoMapper.selectByBuyerId(thirdUserInfo.getThirdUserId(),
				thirdUserInfo.getSource());
		int count = 0;
		if (userInfo == null) {
			thirdUserInfo.setEntryTime(new Date());
			count = thirdUserInfoMapper.insertSelective(thirdUserInfo);
		} else {
			userInfo.setAvatar(StringUtils.isEmpty(thirdUserInfo.getAvatar()) ? null : thirdUserInfo.getAvatar());
			userInfo.setThirdUserId(thirdUserInfo.getThirdUserId());
			userInfo.setNickName(StringUtils.isEmpty(thirdUserInfo.getNickName()) ? null : thirdUserInfo.getNickName());
			userInfo.setSource(thirdUserInfo.getSource());
			userInfo.setUserId(thirdUserInfo.getUserId());
			count = thirdUserInfoMapper.updateByPrimaryKeySelective(userInfo);
		}
		return count;
	}

	@Override
	public List<BusinessWhiteList> getShopperBusinessWhiteList(Integer storeId, Integer shopperId,String code) {
		return businessWhiteListMapper.getShopperBusinessWhiteList(storeId,shopperId,code);
	}

	@Override
	public List<BusinessEncoding> getAllBusinessEncoding() {

		return businessEncodingMapper.getAllBusinessEncoding();
	}

	@Override
	public Integer getShopperRenovationPage(String pageCode,String componentCode,int decorationType) {
		return decorationShopConfigMapper.getShopperRenovationPage(pageCode,componentCode,decorationType);
	}

	@Override
	public Integer getShopperRenovationCustomPage(Integer storeId, String pageCode, String componentCode,int decorationType) {
		return decorationShopConfigMapper.getShopperRenovationCustomPage(storeId,pageCode,componentCode,decorationType);
	}

	@Override
	public List<DecorationShopConfigDetailExtend> getShopperPageDetail(Integer storeId,int decorationType) {
		return decorationShopConfigDetailMapper.getShopperPageDetail(storeId,decorationType);
	}
	
	@Override
	public List<DecorationShopConfigDetailExtend> getShopperDefaultPageDetail(int decorationType) {
		return decorationShopConfigDetailMapper.getShopperDefaultPageDetail(decorationType);
	}

	@Override
	public boolean getShopperRenovationStyleByStoreId(Integer storeId, int decorationType) {
		Integer count = decorationSuitShopMapper.getShopperRenovationStyleByStoreId(storeId, decorationType);
		boolean flag = false;
		if (count != null && count > 0) {
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean getMachineConfig(Integer storeId) {
		Integer count = machineConfigMapper.getMachineConfig(storeId);
		boolean flag = false;
		if (count != null && count > 0) {
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean isSaoBei(Integer storeId, Integer shopperId) {
		Integer count = shopperMapper.isSaobei(storeId,shopperId);
		boolean flag = false;
		if(count !=null && count > 0) {
			flag = true;
		}
		return flag;
	}
	@Override
	public OuterSupport getOuterSupportById(Long id) {
		return outerSupportMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<PayChannel> getAntPayModel(Integer storeId) {
		return payChannelMapper.getAntPayModelByStoreId(storeId);
	}

	@Override
	public ThirdUserInfo getThirdUserInfoById(Long id) {
		return thirdUserInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public DiningArea getDiningAreaByTableName(String tableName,Integer storeId) {
		return diningAreaMapper.getDiningAreaByTableName(tableName,storeId);
	}

	@Override
	public Qrcode getQrcodeInfoByGuid(String guid) {
		return qrcodeMapper.getQrcodeInfoByGuid(guid);
	}

	@Override
	public boolean isWxPay(Integer storeId, Integer shopperId) {
		Integer count = shopperMapper.isWxPay(storeId,shopperId);
		boolean flag = false;
		if(count !=null && count > 0) {
			flag = true;
		}
		return flag;
	}

	@Override
	public int updateIndex(Integer storeId) {
		return shopperMapper.updateIndex(storeId);
	}

	@Override
	public int updateIndexs(Integer storeId, Integer orderType, Integer index) {
		return shopperMapper.updateIndexs(storeId, orderType, index);
	}

	@Override
	public Shopper selectIndex(Integer storeId, Integer orderType) {
		return shopperMapper.selectIndex(storeId, orderType);
	}

	@Override
	public List<PayChannel> findShopPayChannel(Integer payType, Integer storeId, Integer shopperId) {
		return payChannelMapper.findShopPayChannel(payType,storeId,shopperId);
	}

	@Override
	public List<InvoiceServiceInfo> findInvoiceServiceInfo(Integer storeId) {
		return invoiceMapper.findInvoiceServiceInfo(storeId);
	}

    @Override
    public Integer findInvoiceType(Integer storeId) {
        return invoiceMapper.findInvoiceType(storeId);
    }

    @Override
    public List<ShopAddressInfoVO > getNearestStoreAddressInfo(Integer shopperId, Integer storeId, String cityCode, String longitude, String latitude) {
        List<ShopAddressInfo> storeList = new ArrayList<>();
        // 查询当前所在城市中的所有店铺
        if(!Utils.isEmpty(storeId)){
            storeList = shopperMapper.findAllStoreByShopIdAndCityCode(null ,storeId, null, null);
        }else{
            storeList = shopperMapper.findAllStoreByShopIdAndCityCode(shopperId, null, cityCode, null);
        }
        List<ShopAddressInfoVO > shopAddressInfoVOList=new ArrayList<>();
        if (!CollectionUtils.isEmpty(storeList)){

            for (ShopAddressInfo shopAddressInfo:storeList){
                ShopAddressInfoVO shopAddressInfoVO= JSONObject.toJavaObject(JSONObject.parseObject(JSONObject.toJSONString(shopAddressInfo)),ShopAddressInfoVO.class);
                if (!Utils.isEmpty(longitude) && !Utils.isEmpty(shopAddressInfoVO.getLongitude()) && !Utils.isEmpty(latitude)
                        && !Utils.isEmpty(shopAddressInfoVO.getLatitude())){
                    String distance=DistanceUtil.algorithm(Double.valueOf(longitude),Double.valueOf(latitude),
                            Double.valueOf(shopAddressInfoVO.getLongitude()),Double.valueOf(shopAddressInfoVO.getLatitude()));
                    shopAddressInfo.setDistance(distance);
                }
                Integer isStoreDiscount= shopperMapper.isStoreDiscount(storeId,shopperId);
                if (isStoreDiscount>0){
                    shopAddressInfoVO.setIsStoreDiscount(1);//有优惠
                }else {
                    shopAddressInfoVO.setIsStoreDiscount(0);//没有优惠
                }
                shopAddressInfoVOList.add(shopAddressInfoVO);
            }
            if(!Utils.isEmpty(shopAddressInfoVOList)){
                Collections.sort(shopAddressInfoVOList, new Comparator<ShopAddressInfoVO>(){
                    /*
                     * int compare(Person p1, Person p2) 返回一个基本类型的整型，
                     * 返回负数表示：p1 小于p2，
                     * 返回0 表示：p1和p2相等，
                     * 返回正数表示：p1大于p2
                     */
                    public int compare(ShopAddressInfoVO p1, ShopAddressInfoVO p2) {
                        //按照Person的年龄进行升序排列
                        if(!Utils.isEmpty(p1.getDistance()) && !Utils.isEmpty(p2.getDistance())){
                            if(Double.valueOf(p1.getDistance()) > Double.valueOf(p2.getDistance())){
                                return 1;
                            }
                            if(Double.valueOf(p1.getDistance()) == Double.valueOf(p2.getDistance())){
                                return 0;
                            }
                            return -1;
                        }
                        return -1;
                    }
                });
                return shopAddressInfoVOList;
            }
        }
        return shopAddressInfoVOList;
    }

	@Override
	public List<ReserveBasicInfo> getReserveBasicInfo(Integer shopId, Integer storeId) {
		return reserveBasicInfoMapper.getReserveBasicInfo(shopId,storeId);
	}

	@Override
	public List<String> getReserveStageListByStoreId(Integer shopId, Integer storeId) {
		return reserveBasicInfoMapper.getReserveStageListByStoreId(shopId,storeId);
	}

	@Override
	public ReserveBasicInfo getReserveBasicInfoByTime(Integer shopId, Integer storeId, String reserveTime) {
		return reserveBasicInfoMapper.getReserveBasicInfoByTime(shopId,storeId,reserveTime);
	}

	@Override
	public List<ShopperNotice> getNoticeDetail(Integer storeId, String nowDate) {
		return shopperNoticeMapper.getNoticeDetail(storeId,nowDate);
	}

    @Override
    public String getWaimaiBusinessInfo(Integer storeId, Integer takeOutPeriodType) {
        return takeOutConfigMapper.getWaimaiBusinessInfo(storeId,takeOutPeriodType);
    }

    @Override
    public List<Map<String, Object>> getStoreLogoListByStoreIds(List<Long> storeIds) {
        return shopperMapper.getStoreLogoListByStoreIds(storeIds);
    }

    @Override
    public Long getShopIdByAppId(String appId) {
        return shopperMapper.getShopIdByAppId(appId);
    }

    @Override
    public List<PromotionInfoVO> findStorePromotionInfoList(Integer storeId) {
        String nowTime = DateUtils.getNowTime();
        return ruleMapper.findStorePromotionInfoList(storeId,nowTime);
    }

    @Override
    public List<Long> getShopIdListByAppId(String appId) {
        return shopperMapper.getShopIdListByAppId(appId);
    }

    @Override
    public List<String> getThirdUserInfoByMemberUid(String memberUid) {
        return thirdUserInfoMapper.getThirdUserInfoByMemberUid(memberUid);
    }

    @Override
    public List<Map<String, Object>> getMiniConfigChannelAndMiniTypeKey(String appId) {
        return shopperMapper.getMiniConfigChannelAndMiniTypeKey(appId);
    }

    @Override
    public List<Long> getShopIdListByConfigKey(List<String> configKeys, String appId) {
        return shopperMapper.getShopIdListByConfigKey(configKeys,appId);
    }

    @Override
    public ShopBusinessInfoVo getShopBusinessInfo(Integer storeId) {
        String nowDate = DateUtils.getNowTime();
        return takeOutConfigMapper.getShopBusinessInfo(storeId,nowDate);
    }


    @Override
    public double findShopperBagPrice(Integer storeId) {
        return shopperConfigMapper.findShopperBagPrice(storeId);
    }

    @Override
    public Object findShopperConfigByShopperId(Integer storeId, String ctr_vip_chain_store) {
        return shopperExtendMapper.findShopperConfigByShopperId(storeId,ctr_vip_chain_store);
    }

    @Override
    public Map<String, Object> getShopLatAndLng(Integer storeId, Integer takeOutMethod) {
        return takeOutThirdShopInfoMapper.getShopLatAndLng(storeId,takeOutMethod);
    }

    @Override
    public TakeOutBilling findTakeOutBillingList(Integer storeId, Integer configId) {
        return takeOutBillingMapper.findTakeOutBillingList(storeId,configId);
    }

    @Override
    public Map<String, Object> getBusinessTime(Integer storeId) {
        return shopperExtendMapper.getBusinessTime(storeId);
    }

    @Override
    public List<Map<String, Object>> findShopPeriod(Integer storeId) {
        return takeOutPeriodMapper.findShopPeriod(storeId);
    }

    @Override
    public Integer updateOrderSeq(Integer storeId, int orderType) {
        String index = orderType==1?"out_index":"in_index";
        List<Map<String, Object>> list = new ArrayList<>();
        list = hotGoodsWeekMapper.selectIndexByStoreId(storeId,orderType);
        if (Utils.isEmpty(list)) {
            return 0;
        }
        Map<String, Object> shopMap = list.get(0);
        String nowDate = CalendarUtil.formatDateByString(new Date());
        if (shopMap == null|| Utils.isEmpty(shopMap.get("shop_hours")) || !nowDate.equals(shopMap.get("shop_hours").toString())) {
            hotGoodsWeekMapper.updateHourByStoreId(storeId,CalendarUtil.formatDateByString(new Date()));
        }else{
            hotGoodsWeekMapper.updateIndexByStoreId(storeId,orderType);
        }
        list = hotGoodsWeekMapper.selectIndexByStoreId(storeId,orderType);
        return (Integer) list.get(0).get(index);
    }

    @Override
    public TakeOutConfig getTakeOutConfigByStoreId(Integer storeId) {
        return takeOutConfigMapper.getTakeOutConfigByStoreId(storeId);
    }

    @Override
    public String findAlipayStoreIdByShopper(Integer storeId) {
        return thirdPartyAuthorizationMapper.findAlipayStoreIdByShopper(storeId);
    }
}
